// pages/search/search.js
import { searchCourse } from '../../api/search'

Page({
  data: {
    keyword: '',
    historyList: [],
    courseList: [],
    total: 0,
    pageNum: 1,
    pageSize: 10,
    hasMore: true,
    loading: false,
    searched: false
  },
  goIntroduct(data){
    let id = data.currentTarget.dataset.id;
    console.log(data);
   wx.navigateTo({
     url: `/pages/introduct/introduct?courseId=${id}`,
   })
  },
  onLoad() {
    const h = wx.getStorageSync('searchHistory') || []
    this.setData({ historyList: h })
  },

  /* 输入 */
  onInput(e) {
    const kw = e.detail.value.trim()
  this.setData({ keyword: kw })

  // 关键词删空时，把历史重新读出来
  if (!kw) {
    const h = wx.getStorageSync('searchHistory') || []
    this.setData({ historyList: h })
  }

  },

  /* 回车/点历史 */
  async onSearch() {
    const { keyword } = this.data
    if (!keyword) return
    this.saveHistory(keyword)
    this.setData({ pageNum: 1, courseList: [], hasMore: true ,searched: true})
    await this.fetchData()
  },


  /* 拉数据 */
  async fetchData() {
    this.setData({ loading: true })
    const { keyword, pageNum, pageSize } = this.data
  
    // 1. 打印请求参数
    
    try {
      const res = await searchCourse({ keyword, pageNum, pageSize })
  
      // 2. 打印原始响应
      console.log('【原始响应】', res)
  
      // 3. 取出列表/总数（兼容两种常见结构）
      const list = res.courseList || res.data?.records || res.data?.list || []
      const total = res.total || res.data?.total || 0
  
      console.log('【取到的列表】', list)
      console.log('【取到的总数】', total)
  
      // 4. 合并分页
      const merged = this.data.courseList.concat(list)
      console.log('【合并后列表长度】', merged.length)
  
      this.setData({
        courseList: merged,
        total,
        hasMore: merged.length < total,
        loading: false
      })
    } catch (e) {
      console.error('【接口异常】', e)
      console.log('searchCourse=', searchCourse)
      this.setData({ loading: false })
      wx.showToast({ title: '加载失败', icon: 'none' })
    }
  },

  /* ---- 历史 ---- */
  saveHistory(kw) {
    const list = [kw, ...this.data.historyList.filter(i => i !== kw)].slice(0, 8)
    this.setData({ historyList: list })
    wx.setStorageSync('searchHistory', list)
  },
  tapHistory(e) {
    const kw = e.currentTarget.dataset.item
    this.setData({ keyword: kw })
    this.onSearch()
  },
  delOne(e) {
    const kw = e.currentTarget.dataset.item
    const list = this.data.historyList.filter(i => i !== kw)
    this.setData({ historyList: list })
    wx.setStorageSync('searchHistory', list)
  },
  clearAll() {
    wx.showModal({
      title: '提示',
      content: '清空全部历史？',
      success: res => res.confirm && this.setData({ historyList: [] })
    })
  }
})